package dubbot

import (
	"github.com/hyperway/pkg/config"
	"github.com/hyperway/pkg/constant"
	"gopkg.in/yaml.v2"
	"sync"
)

type (
	Config struct {
		Protocol      string   `json:"Protocol" yaml:"Protocol"`   // 协议
		Group         string   `json:"group" yaml:"group"`         // 分组
		Version       string   `json:"version" yaml:"version"`     // 版本
		InterfaceName string   `json:"interface" yaml:"interface"` // 接口名
		Method        string   `json:"method" yaml:"method"`       // 方法名
		Types         []string `json:"types" yaml:"types"`         // 参数类型
	}
)

var (
	consumerConfig = make(map[string]*Config)
	cOnce          sync.Once
)

// AddConsumerConfig 添加消费者配置
func AddConsumerConfig(configId string, config *Config) {
	if config.Protocol == "" {
		config.Protocol = constant.Dubbo
	}
	consumerConfig[configId] = config
}

// GetConsumerConfig 获取消费者配置
func GetConsumerConfig(configId string) (*Config, bool) {
	service, ok := consumerConfig[configId]
	return service, ok
}

// 加载dubbo消费者配置
func loadConsumerConfig() error {
	cOnce.Do(func() {
		conf := config.GlobalConfig().GetStringMap(constant.DubboConsumerConfig)
		for key, value := range conf {
			data, _ := yaml.Marshal(value)
			service := &Config{}
			err := yaml.Unmarshal(data, &service)
			if err != nil {
				panic(err)
			}
			AddConsumerConfig(key, service)
		}
	})
	return nil
}
